#include "rpc_param.h"
#include <stdio.h>

int main() {
	CLIENT *cl;
	char *resultado = (char *) malloc(1000000 * sizeof(char));					
	char *query = (char *) malloc(500 * sizeof(char));
	enum ret_query;
	int i;
	struct timeval t1, t2;
	double tt1, tt2 , tt , ttf=0, ttfq = 0;
  	
	//cria a conexao com o servidor na maquina x-men
	cl = clnt_create("x-men", RPC_PARAM_PROG, RPC_PARAM_VERSION, "tcp");
	if (cl == NULL) {
		fprintf(stderr, "Falhou.\n");
		exit(1);
	}
	
	/* cria autenticacao UNIX
		O cliente autenticado eh identificado pelo servidor*/
	auth_destroy((AUTH *) cl->cl_auth);
	cl->cl_auth = (AUTH *) authunix_create_default();
	
	// Executa 100 insercoes

	for (i = 0; i < 100; i++) {
		gettimeofday(&t1, NULL);
		tt1 =  (t1.tv_sec * 1000000) + t1.tv_usec;

		sprintf(query,"INSERT INTO funcionarios(nome, cargos) VALUES('Funcionario%d', 'cargos%d');",i, i);
		
		if (query_1(&query,&resultado, cl) != RPC_SUCCESS) {
			fprintf(stderr, "Falha no RPC\n");
			exit(1);
		}

		gettimeofday(&t2, NULL);
		tt2 =  (t2.tv_sec * 1000000) + t2.tv_usec;


		tt = tt2 - tt1;
		ttf += tt;
		ttfq += tt;
		printf("Query: %s\n", query);
		printf("Resultado:\n");
		printf("Tempo Total: %f\n\n", tt);
	}
	

  	printf("Tempo total medio de insercoes : %f\n\n", ttfq/100);	
	ttfq=0;	

	// Executa 100 selecoes
	for (i = 0; i < 100; i++) {
		gettimeofday(&t1, NULL);
		tt1 =  (t1.tv_sec * 1000000) + t1.tv_usec;

		sprintf(query, "SELECT * FROM funcionarios WHERE id=%d;",i);
		
		if (query_1(&query,&resultado, cl) != RPC_SUCCESS) {
			fprintf(stderr, "Falha no RPC\n");
			exit(1);
		}

		gettimeofday(&t2, NULL);
		tt2 =  (t2.tv_sec * 1000000) + t2.tv_usec;
		
		tt = tt2 - tt1;
		ttf += tt;
		ttfq += tt;
		printf("Query: %s\n", query);
		printf("Resultado:\n%s", resultado);
		printf("Tempo Total: %f\n\n", tt);
	}

	printf("Tempo total medio de selecoes : %f\n\n", ttfq/100);
	ttfq=0;

	// Executa 100 remocoes

	for (i = 0; i < 100; i++) {
		gettimeofday(&t1, NULL);
		tt1 =  (t1.tv_sec * 1000000) + t1.tv_usec;
		
		sprintf(query, "DELETE FROM funcionarios WHERE Nome='Fulano%d';", i);
	
		if (query_1(&query,&resultado, cl) != RPC_SUCCESS) {
			fprintf(stderr, "Falha no RPC\n");
			exit(1);
		}

		gettimeofday(&t2, NULL);
		tt2 =  (t2.tv_sec * 1000000) + t2.tv_usec;
		
		tt = tt2 - tt1;
		ttf += tt;
		ttfq += tt;
		printf("Query: %s\n", query);
		printf("Resultado:\n");	
		printf("Tempo Total: %f\n\n", tt);
	}

	printf("Tempo total medio de remocoes : %f\n\n", ttfq/100);

	printf("\nTempo Total Final: %.6f\n", ttf);
	free(resultado);
	free(query);
	return 0;
}
